package com.aioething.iot.utils;


import cn.hutool.core.util.IdUtil;
import com.aioething.iot.beans.Node;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TreeUtils {

    public static List<? extends Node> build(List<? extends Node> nodes) {
        List<Node> ret = new ArrayList<>();

        // 筛选出父节点
        Iterator<? extends Node> it = nodes.iterator();
        while (it.hasNext()) {
            Node node = it.next();
            long count = nodes.stream().filter(item->item.getValue().equals(node.getParentCode())).count();
            if (count == 0) { // 不存在父节点的即为父节点
                ret.add(node);
            }
        }

        for (Node node : ret) {
            packChildren(node, nodes);
        }
        return ret;
    }

    public static void packChildren(Node pnode, List<? extends Node> nodes) {
        for (Node node : nodes) {
            if (pnode.getValue().equals(node.getParentCode())) {
                pnode.add(node);
                packChildren(node, nodes);
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(IdUtil.fastSimpleUUID());
    }
}
